#include "player.h"

#include <iostream>

#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Window/Input.hpp>

#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Image.hpp>

template<typename T>
int sign(T i) { return i < 0 ? -1 : 1; }

const sf::Vector2f Player::MaxSpeed(1,1);

Player::Player(const sf::Input &input) :
    sf::Sprite(),
    m_input(input)
{
    SetBlendMode(sf::Blend::Alpha);
    // Change its properties
    SetColor(sf::Color(0, 128, 255, 255));
    m_positions.push_back(sf::Vector2f(200.0f, 100.0f));
	m_speed = sf::Vector2f(0.0f, 0.0f);

    //SetScale(float(Width), float(Height));	// A mesurer
    
	Resize (float(Width), float(Height));

	SetPosition(m_positions.back());
}

Player::~Player(void)
{
}

void Player::update(float elapsedTime)
{
    if (m_input.IsKeyDown(sf::Key::Left)) {
		m_speed.x -= 5 * elapsedTime;
        //Rotate(2.5);
    }

    if (m_input.IsKeyDown(sf::Key::Right)) {
		m_speed.x += 5 * elapsedTime;
        //Rotate(-2.5);
    }

	// gravite
	m_speed.y += 2 * elapsedTime;
	
	if (abs(m_speed.y) >= MaxSpeed.y)
		m_speed.y = sign(m_speed.y)*MaxSpeed.y;

	if (abs(m_speed.x) >= MaxSpeed.x)
		m_speed.x = sign(m_speed.x)*MaxSpeed.x;

    Move(m_speed);

    sf::Vector2f delta = GetPosition() - m_positions.back();

	// Add sprites to the trail when distance is big enough
    if (abs(delta.y) > Height/2 || abs(delta.x) > Width/2) {
        m_positions.push_back(GetPosition());
		// remove trail when there is more than a specific value
	    if (m_positions.size() > 20)
		    m_positions.pop_front();
    }
}

void Player::Render(sf::RenderTarget &target) const
{
    // Draw the trail.
	float id = 0.0f;
    sf::Sprite trail;
    trail.SetColor(GetColor());

	trail.SetBlendMode(sf::Blend::Alpha);

    size_t size = m_positions.size();

	// Draw the player and its trail
	for (std::list<sf::Vector2f>::const_iterator pos = m_positions.begin(); 
			pos != m_positions.end(); 
			++pos)
	{
        sf::Color c(trail.GetColor());
        sf::Uint8 alpha(255 * (id / size));
        c.a = alpha;
        trail.SetColor(c);
        trail.SetPosition(TransformToLocal(*pos));
        target.Draw(trail);
		++id;
	}
}
